<?php
/**
 * Created by PhpStorm.
 * User: kun
 * Date: 26/6/19
 * Time: 18:20
 */

namespace app\api\controller\v1;


use app\api\controller\Common;
use app\common\lib\Aes;
use app\common\lib\ali\Sms;
use app\common\lib\Alidayu;
use app\common\lib\exception\ApiException;
use app\common\lib\IAuth;
use app\common\model\User;
use think\Exception;

class Login extends Common
{
    /**
     * app登陆
     * @return array
     * @throws \think\exception\DbException
     */
    public function save()
    {
        if (!request()->isPost()) {
            return show(config('code.error'), '您没有权限', 403);
        }

        $obj = new Aes();
        $param = input('param.');
        if (empty($param['phone'])) {
            return show(config('code.error'), '手机号不合法', 404);
        }

        if (empty($param['code']) && empty($param['password'])) {
//            $param['code'] = $obj->decrypt($param['code']);
            return show(config('code.error'), '手机短信验证码或密码不合法', 404);
        }
        if (!empty($param['code'])) {
            $code = Sms::getInstance()->checkSmsIdentify($param['phone']);
            if ($code != $param['code']) {
                return show(config('code.error'), '手机短信验证码错误', 404);
            }
        }


        $token = IAuth::setAppLoginToken($param['phone']);

        $data = [
            'token' => $token,
            'time_out' => strtotime("+" . config('app.login_time_out_day') . " day"),
            'last_login_time' => time(),
            'last_login_ip' => request()->ip(),
        ];

        //查询手机号是否存在
        $user = User::get(['phone' => $param['phone']]);
        if ($user && $user->status == config('code.app_status_success')) {
            if (!empty($param['password'])) {
                //判断用户名密码
                if (IAuth::setPassword($param['password']) != $user->password) {
                    return show(config('code.error'), '密码不正确', [], 403);
                }
            }
            //更新
            $id = model('User')->save($data, ['phone' => $param['phone']]);
        } else {
            if (!empty($param['code'])) {
                //第一次登陆 注册数据
                $data['username'] = config('app.app_username') . $param['phone'];
                $data['status'] = 1;
                $data['phone'] = $param['phone'];
                $id = model('User')->add($data);
            } else {
                return show(config('code.error'), '用户不存在', [], 403);
            }

        }


        if ($id) {
            $result = [
                'token' => $obj->encrypt($token . "||" . $id),
            ];
            return show(config('code.success'), 'ok', $result);
        } else {
            return show(config('code.error'), '登陆失败', [], 404);
        }

    }


}

